package com.fastlib.base;

import java.lang.reflect.Field;

import com.fastlib.annotation.ViewInject;

import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;

/**
 * 基础的activity.注解视图绑定id，默认有toolbar
 * 
 * @author sgfb
 */
public abstract class FastActivity extends AppCompatActivity{
	
	protected abstract ActivityConfig initConfig(ActivityConfig config);
	
	protected Toolbar mToolbar;
	private ActivityConfig mConfig=null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		mConfig=initConfig(new ActivityConfig());		
	}
	
	@Override
	public void setContentView(@LayoutRes int resId){
		super.setContentView(resId);
		injectView();
	}
	
	@Override
	public void setContentView(View v){
		super.setContentView(v);
		injectView();
	}
	
	private void injectView(){
		Field[] fields=getClass().getDeclaredFields();
		
		if(fields!=null&&fields.length>0){
			for(Field field:fields){
				try {
					field.setAccessible(true);
					if(field.get(this)!=null)
						continue;
					ViewInject inject=field.getAnnotation(ViewInject.class);
					if(inject!=null)
					    field.set(this,findViewById(inject.id()));
				}catch(IllegalAccessException | IllegalArgumentException e) {
					e.printStackTrace();
				}
			}
		}
		if(mConfig!=null&&mConfig.getToolbarId()!=0){
			String title=mConfig.getTitle();
			mToolbar=(Toolbar)findViewById(mConfig.getToolbarId());
			if(title!=null)
				mToolbar.setTitle(title);
			setSupportActionBar(mToolbar);
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu){ 
		if(mConfig!=null&&mConfig.getMenuId()!=0){
			MenuInflater menuInflater=new MenuInflater(this);
			menuInflater.inflate(mConfig.getMenuId(), menu);
		}
		return true;
	}
	
	public class ActivityConfig{
		//title要在setSupportActionBar前加入
		private String mTitle;
		private int mToolbarId;
		private int mMenuId;
		
		public void setToolbarId(int id){
			mToolbarId=id;
		}
		
		public int getToolbarId(){
			return mToolbarId;
		}
		
		public void setMenuId(int id){
			mMenuId=id;
		}
		
		public int getMenuId(){
			return mMenuId;
		}

		public String getTitle() {
			return mTitle;
		}

		public void setTitle(String title) {
			mTitle = title;
		}
		
		public void setTitle(int res){
			mTitle=FastActivity.this.getString(res);
		}
	}
}